using System.Collections.Generic;

namespace StackCalc.Instructions
{
	public class Copy : IInstruction
	{
		public void Execute(List<IInstruction> stack, StackEngine stackEngine)
		{
			// pop top argument
			INumericInstruction argument = stack.PopInstructionFromTop(1) as INumericInstruction;

			if (argument != null)
			{
				if (argument.NumericValue == 1)
				{
					stack.Add(new PushInteger(1));
				}
				else
				{
					// offset -1 has to be used now
					stack.Add(stack.PeekInstructionFromTop(argument.NumericValue - 1));
				}
			}
		}

		public string Validate(List<IInstruction> stack)
		{
			if (stack.Count == 0)
			{
				return "Not enough elements on stack!";
			}

			// get argument, should be numeric
			INumericInstruction argument = stack.PeekInstructionFromTop(1) as INumericInstruction;

			if (argument == null)
			{
				return "Argument not numeric!";
			}

			if (stack.Count < argument.NumericValue)
			{
				return "Less than" + argument.NumericValue + " elements on stack!";
			}

			if (argument.NumericValue <= 0)
			{
				return "Argument " + argument.NumericValue + " not positive!";
			}

			return string.Empty;
		}
	}
}